package com.manong.bookstore.user.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class CheckExpire implements Runnable{
	private int userSessionScanInterval;
	private long userSessionTimeout;
	private UserSessionManager userSessionManager;

	public CheckExpire(@Value("${userSessionScanInterval}") int userSessionScanInterval, @Value("${userSessionTimeout}")long userSessionTimeout, @Autowired UserSessionManager userSessionManager) {
		this.userSessionScanInterval = userSessionScanInterval;
		this.userSessionTimeout = userSessionTimeout;
		this.userSessionManager = userSessionManager;

		new Thread(this).start();
		System.out.printf("-> CheckExpire: userSessionTimeout=%dms userSessionScanInterval=%dms\n", this.userSessionTimeout, this.userSessionScanInterval);
		System.out.println("-> CheckExpire: thread started.");
	}

	@Override
	public void run() {
		while(true) {
			try {
				Thread.sleep(userSessionScanInterval);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			synchronized (userSessionManager) {
//				System.out.println("CheckExpire: checking");

				Map<String, UserSession> sessions = userSessionManager.getUserSessions();
				Set<String> remove = new HashSet<>();
				long currentTime = System.currentTimeMillis();

				for (String key : sessions.keySet()) {
					UserSession userSession = sessions.get(key);

					if (currentTime - userSession.getLastAccessTime() > userSessionTimeout) {
						remove.add(key);
					}
				}

				for (String key : remove) {
					System.out.println(key + " is timeout.");
					sessions.remove(key);
				}

				remove = null;
			}
		}
	}
}
